<?php
/*
 * @Date: 2020-05-03 22:03:52
 * @名称: 上传控制器
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-18 23:31:20
 * @FilePath: /服务器/app/serverLocalhost/controller/updateController.php
 */

namespace app\serverLocalhost\controller;

use sina\sina;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\facade\View;

class UpdateController
{
    public function imagesUpdate()
    {

        $time = input('get.time'); //@ 时间戳
        if ($time + 3600 > time()) {
            $database_table_name = base64_decode(input("get.database_table_name")); //要插入数据库大的名称
            $pictureCloudAcceleration = input('get.pictureCloudAcceleration'); //图片加速方式 sina/新浪 bilibili/哔哩哔哩 localhost/本服务器
            $encryption_bookId = input('get.encryption_bookId'); //@ 书籍id 加密后
            $encryption_projectId = input('get.encryption_projectId'); //@ 章节id 加密后
            $bookId = input('get.bookId'); //@ 书籍id 加密前
            $projectId = input('get.projectId'); //@ 章节id 加密前
            $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后
            $hashHmac_projectId = hash_hmac("sha256", $projectId . $time, config("globalsettings.serverLocalhost_Edit_sha256Encryption")); //加密后

            if ( //判断加密验证是否一样
                $encryption_bookId ==
                $hashHmac_bookId &&
                $encryption_projectId ==
                $hashHmac_projectId
            ) {

                /**
                 * 接收文件
                 */
                $file = Request::file('file');
                /**
                 * 判断接收文件是否为空
                 */
                if ($file == null) {
                    return json_decode(errorJsonReturn("updateController-Save-10004")->getContent(), true);
                }
                /**
                 * 获取文件扩展名
                 * 可得到上传文件后缀
                 */
                $extension = $file->getOriginalExtension();
                /**
                 * 判断上传文件是否合法
                 * 判断截取上传文件名是否为
                 * jpeg，jpg，png其中之一
                 */
                if (!in_array($extension, array("jpg", "jpeg", "png", "gif"))) {
                    return errorJsonReturn("updateController-Save-10003");
                }

                //解析要插入的数据表
                $database_table_name =  authcode($database_table_name, "DECODE", $bookId . $projectId . $time);

                if ($database_table_name == '') {
                    $project_info = Db::table("book_info_project")
                        ->where([
                            "_id" => $bookId,
                            "chapter_id" => $projectId,
                        ])
                        ->select();
                    if (count($project_info) > 1) {
                        return view('ErrorPage/Error', [
                            "errorCode" => 2006,
                            "errorTitle" => "发生严重错误",
                            "errorMsg" => "这一个漫画id对应多个漫画请尝试修复 这是不允许的操作",
                        ]);
                    }
                    if (count($project_info) < 1) {
                        return view('ErrorPage/Error', [
                            "errorCode" => 2007,
                            "errorTitle" => "发生严重错误",
                            "errorMsg" => "为检索到漫画信息",
                        ]);
                    }
                    if ($project_info[0]["database_table_name"]) {
                        $database_table_name = $project_info[0]["database_table_name"];
                    } else {
                        //todo 待确认
                        $tableName = Db::table('setting')
                            ->where(["id" => 1])
                            ->field(["images_insert_table_name"])
                            ->find();
                        $project_info = Db::table("book_info_project")
                            ->where([
                                "_id" => $bookId,
                                "chapter_id" => $projectId,
                            ])
                            ->update([
                                "images_insert_table_name" => $tableName["images_insert_table_name"],
                            ]);
                        $database_table_name = $tableName["images_insert_table_name"];
                        //todo 待确认
                    }
                }

                $return_data = saverFile(
                    $pictureCloudAcceleration,
                    $file,
                    $bookId,
                    $projectId,
                    $extension,
                    $database_table_name,
                );
            }
        } else {
            $return_data = errorJsonReturn('invalid id');
        }
        return json($return_data);
    }

    public function classCover()
    {
        $time = input('get.time'); //@ 时间戳
        $classId = input('get.classId', 0); //@ 书籍id
        $pictureCloudAcceleration = input('get.pictureCloudAcceleration'); //图片加速方式 sina/新浪 bilibili/哔哩哔哩 localhost/本服务器
        $encryption_bookId = input('get.encryption_bookId'); //@ 书籍id 加密后
        $hashHmac_bookId = hash_hmac("sha256", $classId . $time, config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后
        if ( //判断加密验证是否一样
            $encryption_bookId ==
            $hashHmac_bookId
        ) {
        } else {
            return errorJsonReturn("updateController-Comics-10000");
        }
        if ($time + 3600 < time()) {
            return json_decode(errorJsonReturn("updateController-Save-10002")->getContent(), true);
        }

        /**
         * 接收文件
         */
        $file = Request::file('file');
        /**
         * 判断接收文件是否为空
         */
        if ($file == null) {
            return json_decode(errorJsonReturn("updateController-Save-10004")->getContent(), true);
        }
        /**
         * 获取文件扩展名
         * 可得到上传文件后缀
         */
        $extension = $file->getOriginalExtension();
        /**
         * 判断上传文件是否合法
         * 判断截取上传文件名是否为
         * jpeg，jpg，png其中之一
         */
        if (!in_array($extension, array("jpg", "jpeg", "png", "gif"))) {
            return errorJsonReturn("updateController-Save-10003");
        }
        return json(classCoverUpdate(
            $pictureCloudAcceleration,
            $file,
            $classId,
            $extension,
        ));
    }
    public function bookCover()
    {
        $time = input('get.time'); //@ 时间戳
        $bookId = input('get.bookId', 0); //@ 书籍id
        $pictureCloudAcceleration = input('get.pictureCloudAcceleration'); //图片加速方式 sina/新浪 bilibili/哔哩哔哩 localhost/本服务器
        $encryption_bookId = input('get.encryption_bookId'); //@ 书籍id 加密后
        $hashHmac_bookId = hash_hmac("sha256", $bookId . $time, config("globalsettings.serverLocalhost_Edit_EditComicsInfo_sha256Encryption")); //加密后
        if ( //判断加密验证是否一样
            $encryption_bookId ==
            $hashHmac_bookId
        ) {
        } else {
            return errorJsonReturn("updateController-Comics-10000");
        }
        if ($time + 3600 < time()) {
            return json_decode(errorJsonReturn("updateController-Save-10002")->getContent(), true);
        }

        /**
         * 接收文件
         */
        $file = Request::file('file');
        /**
         * 判断接收文件是否为空
         */
        if ($file == null) {
            return json_decode(errorJsonReturn("updateController-Save-10004")->getContent(), true);
        }
        /**
         * 获取文件扩展名
         * 可得到上传文件后缀
         */
        $extension = $file->getOriginalExtension();
        /**
         * 判断上传文件是否合法
         * 判断截取上传文件名是否为
         * jpeg，jpg，png其中之一
         */
        if (!in_array($extension, array("jpg", "jpeg", "png", "gif"))) {
            return errorJsonReturn("updateController-Save-10003");
        }
        return json(bookCoverUpdate(
            $pictureCloudAcceleration,
            $file,
            $bookId,
            $extension,
        ));
    }
}

/*
 * 保存文件
 * @param String $pictureCloudAcceleration 图片加速方式 sina/新浪 bilibili/哔哩哔哩 localhost/本服务器
 * @param Array $file 文件信息
 * @param [type] $bookId 书籍id
 * @param [type] $projectId//分卷id
 * @param [type] $extension//扩展名
 * @return String 文件路径
*/
function saverFile(
    $pictureCloudAcceleration,
    $file,
    $bookId,
    $projectId,
    $extension,
    $insertTableName
) //保存文件
{
    $token = cookie("Authorization");;
    $userTokenVerificationParse = ParseUserToken($token, true);
    if ($userTokenVerificationParse['code'] != 200) {
        return json($userTokenVerificationParse);
    }
    $user_info = $userTokenVerificationParse["data"]["user_info"];

    switch ($pictureCloudAcceleration) {
        case 'sina':
            // $filename = request()->domain() . "/$saverFileSrc/" . $saverFileName . $extension;
            // $sina = new sina;
            // $return = $sina->upload($filename, $sina->login('17660712176', 'juyaobin'), false);
            // $new = json_decode($return, true);
            // $pic_1 = $new['data']['pics']['pic_1'];
            // $pid = $pic_1['pid'];
            // $img = $sina->getImageUrl($pid, 0);
            // $return_data = json([
            //     "code" => 0,
            //     "error" =>  '1111',
            // ]);
            return json_decode(errorJsonReturn("暂时维护 请选择本机")->getContent(), true);
            break;
        case 'bilibili':

            //!存储备份文件
            $saverFileSrc = "$insertTableName/$bookId/$projectId/$user_info[_id]";
            $saverFileName = "images-" . get_char(time()) . '-' . randIdStructure(123456789, 32); //文件保存名
            $imagesId = randIdStructure(9999999999999999999, 25); //图片id
            $saverFileSrc = Filesystem::disk('BacktrackingImages')->putFileAs($saverFileSrc, $file, "$saverFileName.$extension"); //@tested 这是一个备份存储的

            if ($saverFileSrc) {
                //@tested 上传文件返回状态
                /* array(3) {
                    ["code"]=>
                    int(0)
                    ["message"]=>
                    string(7) "success"
                    ["data"]=>
                    array(3) {
                      ["image_url"]=>
                      string(74) "http://i0.hdslb.com/bfs/album/9dfd49149bc19ddaf4ad8e6a3d36a1e586e4f96e.png"
                      ["image_width"]=>
                      int(400)
                      ["image_height"]=>
                      int(400)
                    }
                  } */
                $returnState = json_decode(bilibiliUpdate('https://api.vc.bilibili.com/api/v1/drawImage/upload', Filesystem::disk('BacktrackingImages')->path($saverFileSrc)), true);
                if ($returnState["code"] == 0 && $returnState["message"] == 'success') { //@d 判断有没有上传成功
                    $image_url = $returnState['data']['image_url'];
                }

                preg_match("/^(\w+:\/\/)?([^\/]+)/i", $image_url, $matches);
                // 获得主机名
                $host = $matches[0]; //@a正则匹配域名 http开头
                $body = explode("$host", $image_url)[1]; //@d正则匹配的请求参数 $host+这个 = 请求地址
                $request = explode(".", $body)[0]; //@d 请求路径
                $extension = explode(".", $body)[1]; //@a扩展名
                // echo $host . "\n";
                Db::table($insertTableName)
                    ->insert([
                        "frame_id" => "$imagesId",
                        "original_name" => explode('.', $file->getOriginalName())[0],
                        "path" =>  $request,
                        "extension" => $extension,
                        "file_server" => $host,
                        "project_id" => $projectId,
                        "_id" => $bookId,
                        "state" => 1,
                        "user_id" => "$user_info[_id]",
                        "save_file_name" => "$saverFileName",
                        "is_local_file" => 0,
                        "backup_files" => "$saverFileSrc",
                        "image_server_host" => config('GlobalSettings.image_sever')
                    ]);

                return json_decode(successJsonReturn([
                    "frame_id" => "$imagesId",
                    "original_name" => explode('.', $file->getOriginalName())[0],
                    "image_sever" => config("globalsettings.image_sever"),
                    "service" =>  $insertTableName,
                ])->getContent(), true);
            } else {
                return json_decode(errorJsonReturn("updateController-Save-10000")->getContent(), true);
            }


            var_dump($file->getFileInfo());
            return;
            return json_decode(errorJsonReturn("暂不支持哔哩哔哩节点 请选择新浪或本机")->getContent(), true);
            break;
        case 'localhost':
            $saverFileSrc = "$insertTableName/$bookId/$projectId/$user_info[_id]";
            $saverFileName = "images-" . get_char(time()) . '-' . randIdStructure(123456789, 32); //文件保存名
            $imagesId = randIdStructure(9999999999999999999, 25); //图片id
            $saverFileSrc = Filesystem::disk('ProjectImages')->putFileAs($saverFileSrc, $file, "$saverFileName.$extension");
            if ($saverFileSrc) {

                $request = explode(".", "/$saverFileSrc")[0]; //@d 请求路径
                $extension = explode(".", "/$saverFileSrc")[1]; //@a扩展名
                Db::table($insertTableName)
                    ->insert([
                        "frame_id" => "$imagesId",
                        "original_name" => explode('.', $file->getOriginalName())[0],
                        "path" => "$request",
                        "extension" => $extension,
                        "file_server" => "http://image.sakura.com",
                        "project_id" => $projectId,
                        "_id" => $bookId,
                        "state" => 1,
                        "user_id" => "$user_info[_id]",
                        "save_file_name" => "$saverFileName",
                        "is_local_file" => 1,
                        "image_server_host" => config('GlobalSettings.image_sever')
                    ]);
                return json_decode(successJsonReturn([
                    "frame_id" => "$imagesId",
                    "original_name" => explode('.', $file->getOriginalName())[0],
                    "image_sever" => config("globalsettings.image_sever"),
                    "service" =>  $insertTableName,
                ])->getContent(), true);
            } else {
                return json_decode(errorJsonReturn("updateController-Save-10000")->getContent(), true);
            }
            break;
        default:
            return json_decode(errorJsonReturn("updateController-Save-10001")->getContent(), true);
            break;
    }
}

function classCoverUpdate(
    $pictureCloudAcceleration, //保存到的位置
    $file, //文件
    $_id, //表id  如果插入封面就是被插入封面的_id 如果是插入分类就是分类id
    $extension //扩展名
) //保存封面
{
    $token = cookie("Authorization");;
    $userTokenVerificationParse = ParseUserToken($token, true);
    if ($userTokenVerificationParse['code'] != 200) {
        return json($userTokenVerificationParse);
    }
    $user_info = $userTokenVerificationParse["data"]["user_info"];

    switch ($pictureCloudAcceleration) {
        case 'sina':
            return json_decode(errorJsonReturn("暂时维护 请选择本机")->getContent(), true);
            break;
        case 'bilibili':
            return json_decode(errorJsonReturn("暂不支持哔哩哔哩节点 请选择新浪或本机")->getContent(), true);
            break;
        case 'localhost':
            $imagesId = randIdStructure(9999999999999999999, 150); //图片id
            $saverFileName = "cover-" . get_char(time()) . '-' . randIdStructure(123456789, 32); //文件保存名
            $saverFileSrc =  "$_id";
            $insertTableName = Db::table('setting')
                ->where(['id' => 1])
                ->field('class_cover_table_name')
                ->find()['class_cover_table_name'];
            $saverFileSrc = Filesystem::disk('ClassImages')->putFileAs("$insertTableName$saverFileSrc", $file, "$saverFileName.$extension");
            if ($saverFileSrc) {
                Db::table($insertTableName)
                    ->insert([
                        "frame_id" => "$imagesId",
                        "original_name" => $file->getOriginalName(),
                        "path" => "$saverFileSrc",
                        "file_server" => config("globalsettings.image_sever_cover"),
                        "_id" => $_id,
                        "state" => 1,
                        "user_id" => "$user_info[_id]",
                        "extension" => $extension,
                    ]);
                Db::table("classified_catalogue")
                    ->where([
                        "_id" => $_id,
                    ])
                    ->update([
                        "file_server" => config("globalsettings.image_sever_cover"),
                        "path" => "$insertTableName/$imagesId",
                        "original_name" => "cover$extension"
                    ]);
                return json_decode(successJsonReturn(
                    [
                        "frame_id" => "$insertTableName/$imagesId",
                        "image_sever" => config("globalsettings.image_sever_cover"),
                    ]
                )->getContent(), true);
            } else {
                return json_decode(errorJsonReturn("updateController-Save-10000")->getContent(), true);
            }
            break;
        default:
            return json_decode(errorJsonReturn("updateController-Save-10001")->getContent(), true);
            break;
    }
}


function bookCoverUpdate(
    $pictureCloudAcceleration, //保存到的位置
    $file, //文件
    $_id, //书籍id
    $extension //扩展名
) //保存封面
{
    /**
     * 更新封面数据库 并且删除封面
     *
     * @param [Srting] $insertTableName 插入的表的名字
     * @param [Srting] $_id 漫画的id
     * @param [Srting] $imagesId 图片的id
     * @param [Srting] $original_name 保存的名字
     * @param [Srting] $saverFileSrc 文件的路径 如果是 http的 为 域名/ 后面的
     * @param [Srting] $file_server 图片服务器地址 如果为远程填写http到 / 如果本地的 可以随便填写
     * @param [Srting] $user_info //用户json
     * @param [Srting] $extension 扩展名
     * @param [Srting] $is_local_file 是否为本地文件
     * @param [Srting] $backup_files 备份文件地址 如果是其他床图的 推荐填写
     * @param [Srting] $image_server_host 请求地址 从那个地址 请求 图片id 可以获取到这张图
     * @return void
     */
    function updateDataBase(
        $insertTableName,
        $_id,
        $imagesId,
        $original_name,
        $saverFileSrc,
        $file_server,
        $user_info,
        $extension,
        $image_server_host,
        $is_local_file,
        $backup_files = null
    ) {
        $coverInfo = Db::table($insertTableName)
            ->where([
                "_id" => $_id,
            ])
            ->select();

        foreach ($coverInfo as $key => $value) {
            if ($value['is_local_file'] == 1) {
                Filesystem::disk('ProjectImages')->delete($value["path"]);
            } else {
                Filesystem::disk('BacktrackingImages')->delete($value["backup_files"]);
            }
        }
        Db::table($insertTableName)
            ->where([
                "_id" => $_id,
            ])
            ->delete();

        Db::table($insertTableName)
            ->insert([
                "frame_id" => "$imagesId",
                "original_name" => $original_name,
                "path" => "$saverFileSrc",
                "file_server" => $file_server,
                "_id" => $_id,
                "state" => 1,
                "user_id" => "$user_info[_id]",
                "extension" => $extension,
                "is_local_file" => $is_local_file,
                "backup_files" => $backup_files,
                "image_server_host" => $image_server_host,
            ]);
        Db::table("book_list")
            ->where([
                "_id" => $_id,
            ])
            ->update([
                "file_server" => config("globalsettings.image_sever_cover"),
                "path" => "$insertTableName/$imagesId",
                "original_name" => $original_name,
            ]);
        return json_decode(successJsonReturn(
            [
                "frame_id" => "$insertTableName/$imagesId",
                "image_sever" => config("globalsettings.image_sever_cover"),
            ]
        )->getContent(), true);
    }


    $token = cookie("Authorization");;
    $userTokenVerificationParse = ParseUserToken($token, true);
    if ($userTokenVerificationParse['code'] != 200) {
        return json($userTokenVerificationParse);
    }
    $user_info = $userTokenVerificationParse["data"]["user_info"];


    $imagesId = randIdStructure(9999999999999999999, 150); //图片id

    $saverFileName = "cover-" . get_char(time()) . '-' . randIdStructure(123456789, 32); //文件保存名
    $insertTableName = Db::table('setting')
        ->where(['id' => 1])
        ->field('book_cover_table_name')
        ->find()['book_cover_table_name'];



    switch ($pictureCloudAcceleration) {
        case 'sina':
            return json_decode(errorJsonReturn("暂时维护 请选择本机")->getContent(), true);
            break;
        case 'bilibili':

            //!存储备份文件
            $saverFileSrc = "$insertTableName/$_id/$user_info[_id]";
            $imagesId = randIdStructure(9999999999999999999, 25); //图片id
            $saverFileSrc = Filesystem::disk('BacktrackingImages')->putFileAs($saverFileSrc, $file, "$saverFileName.$extension"); //@tested 这是一个备份存储的

            if ($saverFileSrc) {
                //@tested 上传文件返回状态
                /* array(3) {
                 ["code"]=>
                 int(0)
                 ["message"]=>
                 string(7) "success"
                 ["data"]=>
                 array(3) {
                   ["image_url"]=>
                   string(74) "http://i0.hdslb.com/bfs/album/9dfd49149bc19ddaf4ad8e6a3d36a1e586e4f96e.png"
                   ["image_width"]=>
                   int(400)
                   ["image_height"]=>
                   int(400)
                 }
               } */
                $returnState = json_decode(bilibiliUpdate('https://api.vc.bilibili.com/api/v1/drawImage/upload', Filesystem::disk('BacktrackingImages')->path($saverFileSrc)), true);
                if ($returnState["code"] == 0 && $returnState["message"] == 'success') { //@d 判断有没有上传成功
                    $image_url = $returnState['data']['image_url'];
                }

                preg_match("/^(\w+:\/\/)?([^\/]+)/i", $image_url, $matches);
                // 获得主机名
                $host = $matches[0]; //@a正则匹配域名 http开头
                $body = explode("$host", $image_url); //@d正则匹配的请求参数 $host+这个 = 请求地址
                // echo $host . "\n";
                // echo $body[1];

                return updateDataBase(
                    $insertTableName,
                    $_id,
                    $imagesId,
                    "cover.$extension",
                    $body[1],
                    $host,
                    $user_info,
                    $extension,
                    config("GlobalSettings.image_sever_cover"),
                    0, //!是否为本地文件
                    $saverFileSrc
                );
            } else {
                return json_decode(errorJsonReturn("updateController-Save-10000")->getContent(), true);
            }

            return json_decode(errorJsonReturn("暂不支持哔哩哔哩节点 请选择新浪或本机")->getContent(), true);
            break;
        case 'localhost':
            $saverFileSrc = "bookCover/$insertTableName/$_id/$user_info[_id]";
            $saverFileSrc = Filesystem::disk('ProjectImages')->putFileAs($saverFileSrc, $file, "$saverFileName.$extension");

            if ($saverFileSrc) {
                return updateDataBase(
                    $insertTableName,
                    $_id,
                    $imagesId,
                    "cover.$extension",
                    $saverFileSrc,
                    config("GlobalSettings.image_sever_cover"),
                    $user_info,
                    $extension,
                    config("GlobalSettings.image_sever_cover"),
                    1
                );
            } else {
                return json_decode(errorJsonReturn("updateController-Save-10000")->getContent(), true);
            }
            break;
        default:
            return json_decode(errorJsonReturn("updateController-Save-10001")->getContent(), true);
            break;
    }
}
